const jwt = require('jsonwebtoken');
const User = require('../models/user.model');
const { AppError } = require('./error.middleware');

/**
 * 管理员认证中间件
 */
exports.adminAuth = async (req, res, next) => {
  try {
    let token;

    // 从请求头获取token
    if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
      token = req.headers.authorization.split(' ')[1];
    }

    if (!token) {
      throw new AppError('未提供访问令牌', 401);
    }

    // 验证token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    // 查找用户
    const user = await User.findById(decoded.id);
    if (!user) {
      throw new AppError('用户不存在', 401);
    }

    // 检查用户是否有管理权限
    if (!['admin', 'seller', 'customer_service'].includes(user.role)) {
      throw new AppError('权限不足', 403);
    }

    // 检查账户是否激活
    if (!user.isActive) {
      throw new AppError('账户已被禁用', 403);
    }

    // 将用户信息添加到请求对象
    req.user = {
      id: user._id,
      username: user.name,
      email: user.email,
      role: user.role,
      shopId: user.shopId,
      isActive: user.isActive,
    };

    next();
  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      next(new AppError('访问令牌无效', 403));
    } else if (error.name === 'TokenExpiredError') {
      next(new AppError('访问令牌已过期', 403));
    } else {
      next(error);
    }
  }
};

/**
 * 权限检查中间件
 * @param {Array} permissions 需要的权限列表
 * @param {Boolean} requireAll 是否需要所有权限（默认false，只需要其中一个）
 */
exports.checkPermission = (permissions = [], requireAll = false) => {
  return (req, res, next) => {
    try {
      const user = req.user;

      if (!user) {
        throw new AppError('用户未认证', 401);
      }

      // 获取用户权限
      const userPermissions = getRolePermissions(user.role);

      // 检查权限
      let hasPermission = false;

      if (requireAll) {
        hasPermission = permissions.every(permission => userPermissions.includes(permission));
      } else {
        hasPermission = permissions.some(permission => userPermissions.includes(permission));
      }

      if (!hasPermission) {
        throw new AppError('权限不足', 403);
      }

      next();
    } catch (error) {
      next(error);
    }
  };
};

/**
 * 店铺权限检查中间件
 * 确保用户只能访问自己的店铺资源
 */
exports.checkShopPermission = (req, res, next) => {
  try {
    const user = req.user;
    const shopId = req.params.shopId || req.body.shopId || req.query.shopId;

    // 超级管理员可以访问所有店铺
    if (user.role === 'admin') {
      return next();
    }

    // 商家和客服只能访问自己店铺的资源
    if (user.role === 'seller' || user.role === 'customer_service') {
      if (!user.shopId || user.shopId.toString() !== shopId) {
        throw new AppError('无权访问此店铺资源', 403);
      }
    }

    next();
  } catch (error) {
    next(error);
  }
};

/**
 * 角色检查中间件
 * @param {Array} roles 允许的角色列表
 */
exports.checkRole = (roles = []) => {
  return (req, res, next) => {
    try {
      const user = req.user;

      if (!user) {
        throw new AppError('用户未认证', 401);
      }

      if (!roles.includes(user.role)) {
        throw new AppError('角色权限不足', 403);
      }

      next();
    } catch (error) {
      next(error);
    }
  };
};

/**
 * 获取角色权限列表
 * @param {string} role 用户角色
 * @returns {Array} 权限列表
 */
const getRolePermissions = (role) => {
  const permissions = {
    admin: [
      'user:view', 'user:create', 'user:update', 'user:delete',
      'shop:view', 'shop:create', 'shop:update', 'shop:delete', 'shop:approve', 'shop:view_all',
      'product:view', 'product:create', 'product:update', 'product:delete', 'product:view_all',
      'order:view', 'order:update', 'order:view_all',
      'coupon:view', 'coupon:create', 'coupon:update', 'coupon:delete', 'coupon:create_platform', 'coupon:create_shop',
      'banner:view', 'banner:create', 'banner:update', 'banner:delete',
      'sales:view', 'sales:view_all',
      'chat:view', 'chat:reply', 'chat:manage',
      'system:config', 'system:log',
    ],
    seller: [
      'shop:view', 'shop:update', 'shop:view_own',
      'product:view', 'product:create', 'product:update', 'product:delete', 'product:view_own',
      'order:view', 'order:update', 'order:view_own',
      'coupon:view', 'coupon:create', 'coupon:update', 'coupon:delete', 'coupon:create_shop',
      'sales:view', 'sales:view_own',
      'chat:view', 'chat:reply',
    ],
    customer_service: [
      'chat:view', 'chat:reply',
      'order:view', 'order:view_own',
      'product:view', 'product:view_own',
    ],
  };

  return permissions[role] || [];
};

module.exports = exports;
